package org.example.cake.controller;

import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    public static Map<String,Session> sessionMap = new HashMap<>();
    // 存储所有PC客户端的会话
    private static final ConcurrentHashMap<String, Session> pcSessions = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, Session> miniSessions = new ConcurrentHashMap<>();

    public MyWebSocket() {
        System.out.println("实例化websocket");
    }

    /**
     * 接收前端的支付，然后发送到后端，后端接收到信息就调用数据库
     */

    @OnOpen
    public void onopen(Session session) throws IOException {
//        System.out.println("session------------------------ = " + session);
//        session.getBasicRemote().sendText("您有新的订单");
        // 连接时不需要主动发送消息
        // 通过查询参数区分客户端类型
        String clientType = session.getRequestParameterMap().getOrDefault("clientType", Collections.singletonList("unknown")).get(0);

        if ("pc".equals(clientType)) {
            pcSessions.put(session.getId(), session);
            System.out.println("PC客户端连接: " + session.getId());
        } else {
            miniSessions.put(session.getId(), session);
            System.out.println("小程序客户端连接: " + session.getId());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        //发送信息去前端
        //session.getBasicRemote().sendText("你有新的订单"); // 同步发送
        System.out.println("收到消息: " + message + " from " + session.getId());

        // 广播消息给所有PC客户端
        broadcastToPc(message);
    }
    // 广播消息给所有PC客户端
    private static void broadcastToPc(String message) {
        for (Session session : pcSessions.values()) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

